import React, {useState, useEffect} from "react";
import {Tree, Input, Pagination, Table} from "antd";

import {openNotificationWithIcon} from 'utils/comm';

import styles from './NextNodeSelect.less';

const {TreeNode} = Tree;
const {Search} = Input;

const NextNodeSelect = (props) => {

  const {
    type,
    processInstanceId,
    treeSource,
    handleAdd,
    setOrgList,
    dispatch,
    candidateSetNull,
    // handleDelSelect,
    // treeCheckedKeys,
  } = props;

  const [showSearch, setShowSearch] = useState(false);
  const [keyWord, setKeyWord] = useState('');
  const [pageNo, setPageNo] = useState(1);
  const [total, setTotal] = useState(0);
  const [placeholder, setPlaceholder] = useState('请输入');

  const columns = [
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
      render: (text, record) => (<div className={styles.title} onDoubleClick={() => handleAdd(type, [record])}>{text}</div>),

    },
    // {
    //   title: "所属组织",
    //   dataIndex: "orgName",
    //   key: "orgName",
    //   render: (text, record) =>
    //     record.orgList.map(item => item.orgName).join("，"),
    // },
  ];

  const columnsEmployee = [
    {
      title: "工号",
      dataIndex: "employeeCode",
      key: "employeeCode",
      render: (text, record) => (<div className={styles.title} onDoubleClick={() => handleAdd(type, [record])}>{text}</div>),
    },
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
      render: (text, record) => (<div className={styles.title} onDoubleClick={() => handleAdd(type, [record])}>{text}</div>),
    },
    // {
    //   title: "所属组织",
    //   dataIndex: "orgName",
    //   key: "orgName",
    //   render: (text, record) =>
    //     record.orgList.map(item => item.orgName).join("，"),
    // },
  ];

  useEffect(() => {
    let tmpPlaceholder = '请输入';
    let tmpShowSearch = false;
    if (type === "STA") {
      tmpPlaceholder = '请输入用户姓名或者工号';
      tmpShowSearch = true;
    } else if (type === "ROL") {
      tmpPlaceholder = '请输入角色名称';
      handleSearch('', 1);
      tmpShowSearch = true;
    } else if (type === "GROUP") {
      tmpPlaceholder = '请输入用户组名称';
      handleSearch('', 1);
      tmpShowSearch = true;
    } else if (type === 'POSITION') {
      tmpPlaceholder = '请输入岗位名称';
      handleSearch('', 1);
      tmpShowSearch = true;
    }
    setTotal(0);
    setKeyWord('');
    setPageNo(1);
    setShowSearch(tmpShowSearch);
    setPlaceholder(tmpPlaceholder);
  }, [type]);


  // const onCheck = (keys, e) => {
  //
  //   const {checked, node} = e;
  //
  //   const {children = [], code, name, type: type1, key} = node.props.dataRef;
  //
  //   let hasSubChildren = false;
  //
  //   children.map(item => {
  //
  //     if (item.children && item.children.length > 0) {
  //       hasSubChildren = true;
  //     }
  //     return item;
  //   })
  //
  //   if (checked) {
  //     if (children.length > 0 && !hasSubChildren) {
  //       handleAdd(type, [{code, name, type: type1, key}, ...children]);
  //     } else {
  //       handleAdd(type, [{code, name, type: type1, key}]);
  //     }
  //
  //   } else if (children.length > 0 && !hasSubChildren) {
  //     handleDelSelect([{code, name, type: type1, key}, ...children]);
  //   } else {
  //     handleDelSelect([{code, name, type: type1, key}]);
  //   }
  //
  // };


  const renderTreeNodes = (data) =>
    data.map(item => {
      if (item.children) {
        return (

          <TreeNode
            {...item}
            title={<span className={styles.title} onDoubleClick={() => handleAdd(type, [item])}>{item.name}</span>}
            key={item.key}
            dataRef={item}
          >
            {renderTreeNodes(item.children)}
          </TreeNode>

        );
      }
      return (
        <TreeNode
          key={item.key}
          {...item}
          title={<span className={styles.title} onDoubleClick={() => handleAdd(type, [item])}>{item.name}</span>}
          dataRef={item}
        />

      );
    });


  // 加载子节点
  const onLoadData = treeNode =>
    new Promise(resolve => {
      if (treeNode.props.children) {
        resolve();
        return;
      }

      // const code = treeNode.props.eventKey;
      const {code, type: typ, key} = treeNode.props.dataRef;
      dispatch({
        type: "FlowHandle/getCandidateInfoList",
        payload: {type: typ, code, processInstanceId},
      }).then(({errCode, errMsg, datas}) => {
        if (errCode !== 0) {
          openNotificationWithIcon("error", "", errMsg);
          resolve();
          return;
        }

        const {flowTaskCandidateInfoVos = []} = datas;

        const tmpList = flowTaskCandidateInfoVos.map(item => {
          const {code: code1, name, type: type1} = item;
          return {...item, key: `${key}-${code1}`, title: name, isLeaf: type1 === 'STA'};
        })

        const tmpOrgList = treeSource.map(subItem => {
          const {code: tmpCode} = subItem;
          if (tmpCode === code) {
            // subItem.children = flowTaskCandidateInfoVos;
            subItem.children = tmpList;
          }
          return subItem;
        })
        treeNode.props.dataRef.children = tmpList;
        setOrgList(type, tmpOrgList);
        resolve();
      });

    });

  const handleSearch = (searchValue, pageIndex) => {

    if (!candidateSetNull) {
      return;
    }

    if (type === 'STA') {
      getStaList(searchValue, pageIndex);
    } else if (type === 'ROL') {
      getOrlList(searchValue, pageIndex);
    } else if (type === 'GROUP') {
      getGroupList(searchValue, pageIndex);
    } else if (type === 'POSITION') {
      getPositionList(searchValue, pageIndex);
    }
  }

  const getOrlList = (searchValue, pageIndex) => {
    dispatch({
      type: "FlowChart/getUserRolePageList",
      payload: {roleName: searchValue, pageNo: pageIndex, pageSize: 10},
    }).then(({errCode, datas = [], totalCount = 0}) => {
      if (errCode !== 0) {
        openNotificationWithIcon("error", "", "获取角色信息失败");
        return;
      }

      setTotal(totalCount);

      const newTreeSource = datas.map(item => {
        const {roleCode, roleName} = item;
        return {code: roleCode, name: roleName, type};
      })
      setOrgList(type, newTreeSource)

    });
  };

  const getGroupList = (searchValue, pageIndex) => {
    dispatch({
      type: "FlowChart/getUserGroupPageList",
      payload: {groupName: searchValue, pageNo: pageIndex, pageSize: 10},
    }).then(({errCode, datas = [], totalCount = 0}) => {
      if (errCode !== 0) {
        openNotificationWithIcon("error", "", "获取用户组信息失败");
        return;
      }

      setTotal(totalCount);

      const newTreeSource = datas.map(item => {
        const {groupCode, groupName} = item;
        return {code: groupCode, name: groupName, type};
      })
      setOrgList(type, newTreeSource)

    });
  };

  const getPositionList = (searchValue, pageIndex) => {
    dispatch({
      type: "FlowChart/getUserPositionPageList",
      payload: {positionName: searchValue, pageNo: pageIndex, pageSize: 10},
    }).then(({errCode, datas = [], totalCount = 0}) => {
      if (errCode !== 0) {
        openNotificationWithIcon("error", "", "获取岗位信息失败");
        return;
      }

      setTotal(totalCount);

      const newTreeSource = datas.map(item => {
        const {positionCode, positionName} = item;
        return {code: positionCode, name: positionName, type};
      })
      setOrgList(type, newTreeSource)
    });
  };

  const getStaList = (searchValue, pageIndex) => {
    dispatch({
      type: "usertreeSelect/selectEmployeeList",
      payload: {employeeName: searchValue, pageIndex, pageSize: 10},
    }).then(({errCode, datas}) => {
      if (errCode !== 0) {
        openNotificationWithIcon("error", "", "获取人员信息失败");
        return;
      }
      setTotal(datas?.total ?? 0);
      const {dataList = []} = datas;
      const newTreeSource = dataList.map(item => {
        const {userId = '',employeeCode='', employeeName = ''} = item;
        return {code: userId, name: employeeName, type, employeeCode};
      })
      setOrgList(type, newTreeSource)
    });
  };


  const handlePagination = (pageNumber) => {
    setPageNo(pageNumber);
    handleSearch(keyWord, pageNumber);
  }


  // const rowSelection = {
  //   selectedRowKeys: [...treeCheckedKeys],
  //   onSelect: (record, selected) => {
  //     if (selected) {
  //       handleAdd(type, [record])
  //     } else {
  //       handleDelSelect([record]);
  //     }
  //   },
  //   onSelectAll: (selected, selectedRows, changeRows) => {
  //     if (selected) {
  //       handleAdd(type, changeRows);
  //     } else {
  //       handleDelSelect(changeRows);
  //     }
  //   },
  // }


  return (
    <div className={styles.root}>
      {candidateSetNull && showSearch ? (
        <Search
          placeholder={placeholder}
          onSearch={() => handleSearch(keyWord, pageNo)}
          style={{width: 300, marginBottom: '10px'}}
          onChange={(e) => setKeyWord(e.target.value)}
        />
      ) : null}
      <div style={{height: '350px', overflow: 'scroll'}}>
        {type === 'STA' ? (
          <Table
            columns={candidateSetNull ? columnsEmployee : columns}
            size="small"
            rowKey='key'
            // rowSelection={rowSelection}
            dataSource={treeSource}
            pagination={{}}
          />
        ) : (
          <Tree
            key={type}
            checkStrictly
            // onCheck={onCheck}
            // checkedKeys={[...treeCheckedKeys]}
            loadData={(type && type !== 'STA') ? onLoadData : null}
          >

            {treeSource ? renderTreeNodes(treeSource) : null}
          </Tree>
        )}
      </div>
      {candidateSetNull && showSearch && total > 10 ? (
        <div style={{marginTop: '20px', display: "flex", justifyContent: 'flex-end'}}>
          <Pagination
            showQuickJumper={total > 50}
            defaultCurrent={pageNo}
            current={pageNo}
            total={total}
            showLessItems
            onChange={handlePagination}
          />
        </div>
      ) : null}
    </div>
  );
}


export default NextNodeSelect;


